﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MinistryStandardPlatformWeb.Models;
using MinistryStandardPlatformEntity;

namespace MinistryStandardPlatformWeb.Controllers
{

    [MenuAuthorized("2",Order=1)]
    [IsLogin(Order=0)]
    public class DispatchCenterController : Controller
    {
        //
        // GET: /DispatchCenter/
        private MSPDataContext context = new MSPDataContext();
        private MSPGpsDataContext context1 = new MSPGpsDataContext();
        MinistryStandardPlatformBusiness.DBService.DBHelperClient geoHelper = new MinistryStandardPlatformBusiness.DBService.DBHelperClient();

        public ActionResult Index()
        {
            List<UnitTaskModel> unitTasks = new List<UnitTaskModel>();

            string firstDayOfMonth=DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            //用户下的所有单位
            var units = (from r in context.RightsDetails
                        where r.HasRight == true &&
                        r.NodeTYPE == true &&
                        r.UserId == CommonFunctions.GetLoginUser().UserId
                        select new
                        {
                            UNITID=r.NodeId,
                            UNITNAME=r.NodeName
                        }).Distinct();
            List<string> unitsId=(from u in units
                                 select u.UNITID).ToList();

            //各单位下的车辆总数
            var vehicles=from v in context.InfoVehicle
                         where unitsId.Contains(v.ParentUnitId)
                         group v by v.ParentUnitId into vg
                         select new
                         {
                             unitId=vg.Key,
                             vehicleCount=vg.Count()
                         };

            //各单位下的正在进行任务车辆数
            var vehiclesRunning = from v in context.InfoVehicle
                           where unitsId.Contains(v.ParentUnitId) &&
                           v.VehicleState==1
                           group v by v.ParentUnitId into vg
                           select new
                           {
                               unitId = vg.Key,
                               vehicleCount = vg.Count()
                           };

            //各单位下的空闲车辆数
            var vehiclesFree = from v in context.InfoVehicle
                           where unitsId.Contains(v.ParentUnitId) &&
                           v.VehicleState==0
                           group v by v.ParentUnitId into vg
                           select new
                           {
                               unitId = vg.Key,
                               vehicleCount = vg.Count()
                           };

            //各单位下的不可用车辆数
            var vehiclesUnavaiable = from v in context.InfoVehicle
                           where unitsId.Contains(v.ParentUnitId) &&
                           v.VehicleState!=0
                           group v by v.ParentUnitId into vg
                           select new
                           {
                               unitId = vg.Key,
                               vehicleCount = vg.Count()
                           };

            //各单位下的任务单数
            var tasks = from t in context.TranTaskList
                        where unitsId.Contains(t.unitId) &&
                        t.taskStatus != "2"
                        group t by t.unitId into tg
                        select new
                        {
                            unitId = tg.Key,
                            taskCount = tg.Count()
                        };

            //各单位月累计趟次和月运输总量
            var taskInfo = (from t in context.TranTaskList
                           join d in context.TranTaskListDetail
                           on t.taskListId equals d.tranTaskListId
                           into dt
                           from dtr in dt
                           where Convert.ToInt32(dtr.carStatus)!=6 &&
                           string.Compare(dtr.insertTime, firstDayOfMonth) >= 0
                           select new
                           {
                               unitId = t.unitId,
                               onTrans = dtr.id,
                               cap = dtr.transPerCap
                           }).Distinct();

            var unitTaskInfo = from r in taskInfo
                               group r by r.unitId into rg
                               select new
                               {
                                   unitId = rg.Key,
                                   tranCount = rg.Count(),
                                   volumnCount = rg.Sum(t=>Convert.ToDecimal(t.cap==null?"0":t.cap))
                               };

            var result = from u in units
                         join v in vehicles
                         on u.UNITID equals v.unitId
                         into uv
                         join vr in vehiclesRunning
                         on u.UNITID equals vr.unitId
                         into uvr
                         join vf in vehiclesFree
                         on u.UNITID equals vf.unitId
                         into uvf
                         join vu in vehiclesUnavaiable
                         on u.UNITID equals vu.unitId
                         into uvu
                         join t in tasks
                         on u.UNITID equals t.unitId
                         into ut
                         join ti in unitTaskInfo
                         on u.UNITID equals ti.unitId
                         into uti
                         from uvrow in uv.DefaultIfEmpty()
                         from uvrrow in uvr.DefaultIfEmpty()
                         from uvfrow in uvf.DefaultIfEmpty()
                         from uvurow in uvu.DefaultIfEmpty()
                         from utrow in ut.DefaultIfEmpty()
                         from utirow in uti.DefaultIfEmpty()
                         orderby u.UNITID
                         where utrow!=null
                         select new UnitTaskModel()
                         {
                             UnitId = u.UNITID,
                             UnitName = u.UNITNAME,
                             VehicleNum = uvrow == null ? "0" : uvrow.vehicleCount.ToString(),
                             TaskNum = utrow == null ? "0" : utrow.taskCount.ToString(),
                             BusyVehicleNum = uvrrow == null ? "0" : uvrrow.vehicleCount.ToString(),
                             FreeVehiclieNum = uvfrow == null ? "0" : uvfrow.vehicleCount.ToString(),
                             UnavailableVehicleNum = uvurow == null ? "0" : uvurow.vehicleCount.ToString(),
                             MonthTrip = utirow == null ? "0" : utirow.tranCount.ToString(),
                             MonthVolume = utirow == null ? "0" : utirow.volumnCount.ToString()
                         };

            unitTasks = result.ToList();


            return View(unitTasks);
        }

        public ActionResult Detail(string parameters)
        {
            string unitId = parameters;
            string firstDayOfMonth = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            string today = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");

            List<TaskDetailModel> taskDetails = new List<TaskDetailModel>();

            var tasks = from t in context.TranTaskList
                        where t.unitId == unitId &&
                        t.taskStatus != "2"  //只加载没有完成的任务
                        select new TaskDetailModel()
                        {
                            TaskId = t.taskListId,
                            Destination = t.endRegName,
                            Distance = t.transDistance,
                            Mark = t.concretNum,
                            TotalVolume = t.transTotalCube,
                            CompletedVolume = context.TranTaskListDetail.Where(d=>d.tranTaskListId==t.taskListId && Convert.ToInt32(d.carStatus)!=6 && d.transPerCap!=null).Sum(d=>Convert.ToDecimal(d.transPerCap)),
                            TotalTrip = context.TranTaskListDetail.Where(d => d.tranTaskListId == t.taskListId).Distinct().Count(),
                            DayTrip = context.TranTaskListDetail.Where(d => d.tranTaskListId == t.taskListId && string.Compare(d.insertTime, today) >= 0).Distinct().Count(),
                            Vehicles = (from td in context.TranTaskListDetail
                                       where td.tranTaskListId == t.taskListId
                                       group td by td.vehicleNum
                                           into tdg
                                           let last = tdg.Max(r => r.insertTime)  //最近一个趟次
                                           from v in context.InfoVehicle
                                           from tdgr in tdg
                                           where tdgr.insertTime == last && //如果没有出战时间为空，则按照插入时间来判断
                                           v.Vehiclenum == tdgr.vehicleNum
                                           select new TaskVehicle()
                                           {
                                               TaskId = tdgr.tranTaskListId,
                                               VehicleId = v.VehicleId,
                                               VehicleNum = tdgr.vehicleNum,
                                               TranStatus = parseTranStatus(tdgr.carStatus),
                                               LeaveStationTime = tdgr.outStartRegTime,
                                               ArriveWorkSiteTime = tdgr.inEndRegTime,
                                               ThisTimeVolume = tdgr.transPerCap,
                                               MonthVolume = context.TranTaskListDetail.Where(t1 => t1.vehicleNum == tdgr.vehicleNum && t1.tranTaskListId == tdgr.tranTaskListId && Convert.ToInt32(t1.carStatus) != 6 && string.Compare(t1.insertTime, firstDayOfMonth) >= 0).Sum(t2 => Convert.ToDecimal(t2.transPerCap == null ? "0" : t2.transPerCap)),
                                               MonthTrip = context.TranTaskListDetail.Where(t3 => t3.vehicleNum == tdgr.vehicleNum && t3.tranTaskListId == tdgr.tranTaskListId&& Convert.ToInt32(t3.carStatus) != 6 && string.Compare(t3.insertTime, firstDayOfMonth) >= 0).Select(t4 => t4.id).Distinct().Count()
                                           }).ToList()
                        };
            taskDetails = tasks.ToList();

            foreach (TaskDetailModel item in taskDetails)
            {
                if (item.CompletedVolume == null)
                {
                    item.CompletedVolume = 0;
                }
                if (item.TotalVolume != null && item.TotalVolume != 0)
                {
                    item.CompleteRate = (double)item.CompletedVolume / (double)item.TotalVolume;
                }
                else
                {
                    item.CompleteRate = -1;
                }
            }

            ViewBag.id = parameters;
            return PartialView(taskDetails);
        }

        private string  parseTranStatus(string status)
        {
            switch(status)
            {
                case "1":
                    return "未发车";
                case "2":
                    return "去程";
                case "3":
                    return "工地内卸料";
                case "4":
                    return "回程";
                case "5":
                    return "已回站";
                case "6":
                    return "强制回站";
                default:
                    return "";
            }
        }


        public ActionResult Map(string id)
        {
            List<string> vehicles = new List<string>();
            if (id.StartsWith("VEHI"))
            {
                vehicles.Add(id);
            }
            else
            {
                vehicles = context.TranTaskListDetail.Where(t => t.tranTaskListId == id).Select(t => t.vehicleNum).Distinct().ToList();
            }

            string firstDayOfLastMonth = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-01 00:00:00");
            string now = DateTime.Now.ToString(CommonDictionary.DateTimeStrFormat);

            var gps = from g in context1.GpsBasic
                      where vehicles.Contains(g.vehicleNum)
                      group g by g.vehicleNum
                          into gg
                          let last = gg.Max(t => t.recordtime)
                          from ggr in gg
                          where ggr.recordtime == last
                          select new VehicleRealTimeInfo()
                          {
                              VehicleId = ggr.vehicleId,
                              Time = ggr.recordtime,
                              Longitude = ggr.longitude,
                              Latitude = ggr.latitude,
                              Speed = ggr.speed
                          };
            List<VehicleRealTimeInfo> vehiclesInfo = gps.ToList();
            foreach (VehicleRealTimeInfo v in vehiclesInfo)
            {
                v.Location = geoHelper.GgpsTranslate2BaiduPoi(v.Longitude.ToString(), v.Latitude.ToString());
            }

            ViewBag.id = id; 
            return View(vehiclesInfo);
        }
    }
}
